
'use strict';

const express=require('express');
const path=require('path');
const xtpl=require('xtpl');
const moment=require('moment');

const db=require(path.join(__dirname,"../configs/database.js"));
const base=require(path.join(__dirname,"./baseController.js"));

module.exports.teaStuList=(req,res)=>{

   const page=parseInt(req.query.page||'1');
   const limit=parseInt(req.query.limit||'12');

   const start=(page-1)*limit;
   db.table('student').count("*").then((count)=>{
   
    const totalPage=count%limit==0?count/limit:parseInt(count/limit)+1;
    const totalPageArray=[];
    for(var i=1;i<=totalPage;i++){

    	totalPageArray.push(i);
    }

    db.table('student').join("pre_class  on pre_student.class_id = pre_class.class_id").join("pre_teach on pre_student.teach_id = pre_teach.teach_id").join("pre_course on pre_student.course_id = pre_course.course_id").order("stu_id DESC").limit(start,limit).select().then((data)=>{

   xtpl.renderFile(
     path.join(__dirname,"../views/admin/teaStu_list.html"),
     {

     	array:data,
        totalPage:totalPage,
        totalPageArray:totalPageArray,
        page:page
     },
     (err,content)=>{

     	if(err){
     		return console.log(err);
     	}
     
       res.setHeader("Content-Type","text/html;charset=utf-8");
       res.end(content);
     }
  
   	);



    });
    
       

   });

};


module.exports.teaStuAdd=function(req,res){
  // 查询课程
 db.table('course').select().then(function(datas){

     // 查询班级
  db.table('class').select().then(function(data){
      db.table('teach').select().then(function(datat){
        xtpl.renderFile(
        path.join(__dirname,"../views/admin/teaStu_add.html"),
        {
          crr:datas,
          arr:data,
          trr:datat
        },
        function(err,content){
           res.setHeader("Content-Type","text/html;charset=utf-8");
           res.end(content);   
          }
      );
      });
 });
});
};


// 数据提交


module.exports.teaStuAddData=function(req,res){

  var where=`stu_name='${req.body.stu_name}'` && `stu_cardNum='${req.body.stu_cardNum}'`;
  db.table('student').where(where).find().then(function(data){
   if(JSON.stringify(data) != "{}"){

      res.setHeader("Content-Type","text/html;charset=utf-8");
      res.end("<script>alert('该学生已经存在，请重新添加');location.href='/student/student_add';</script>");
      return false;

   }else{
        
      

     let file = path.basename(req.files.stu_img.path);
     let data={

          "stu_name":req.body.stu_name,
          "class_id":req.body.class_id,
          "teach_sex":req.body.teach_sex,
          "course_id":req.body.course_id,
          "stu_date":(Date.parse(moment(req.body.stu_date))/1000),
          "stu_qq":req.body.stu_qq,
          "stu_tel":req.body.stu_tel,
          "stu_cardName":req.body.stu_cardName,
          "stu_cardNum":req.body.stu_cardNum,
          "stu_address":req.body.stu_address,
          "stu_img":file,
          "teach_id":req.body.teach_id,
          "stu_time":(Date.parse(moment(req.body.stu_time))/1000)
      };

      
   

  


      db.table('student').add(data).then(function(insertId){
          res.redirect('/teaStu/teaStu_list');
          return false;
      }).catch(function(err){
           if(err){
             return console.log(err);
           }
      });
       
   }

  });
 
};

module.exports.teaStuEdite=(req,res)=>{





   // 查课程的信息 老师的信息 班级的信息 学生的信息
   
    var stu_id=req.params.stu_id||0;
    var where=`stu_id=${stu_id}`;

    db.table('student').where(where).find().then(function(data){


        // 查课程的信息
      
      db.table('course').select().then(function(cData){


       //班级的信息
        db.table('class').select().then(function(lData){
         
            //老师的信息
            db.table('teach').select().then(function(datat){

            if(JSON.stringify(data)=="{}"){


               base.showMsg(res,"班级不存在","/student/student_list");

            }else{

         data.stu_time=moment(data.stu_time*1000).format("YYYY-MM-DD");

         data.stu_date=moment(data.stu_date*1000).format("YYYY-MM-DD");

        xtpl.renderFile(
           
          path.join(__dirname,"../views/admin/teaStu_edite.html"),

           {
             
             student:data,
             crr:cData,
             arr:lData,
             trr:datat


           },

          function(err,content){
                res.setHeader("Content-Type","text/html;charset=utf-8");
                res.end(content);
              }

      );


            }
                  


            });

        });
      });
    });


};


module.exports.teaStuEditeData=(req,res)=>{

  var stu_id=req.params.stu_id||0;
  var where=`stu_id=${stu_id}`;

  db.table("student").where(where).find().then(function(data){


    if(JSON.stringify(data)=="{}"){
         base.showMsg(res,"学生不存在",'/teaStu/teaStu_list');
         return false;
    }else{

        var check=`stu_name='${req.body.stu_name}' AND stu_id !=${stu_id}`;

        db.table("student").where(check).find().then(function(data){

        if(JSON.stringify(data)!="{}"){
          
           base.showMsg(res,"该学生已经存在");
           return false;

        }else{

     let file = path.basename(req.files.stu_img.path);
     let data={

          "stu_name":req.body.stu_name,
          "class_id":req.body.class_id,
          "teach_sex":req.body.teach_sex,
          "course_id":req.body.course_id,
          "stu_date":(Date.parse(moment(req.body.stu_date))/1000),
          "stu_qq":req.body.stu_qq,
          "stu_tel":req.body.stu_tel,
          "stu_cardName":req.body.stu_cardName,
          "stu_cardNum":req.body.stu_cardNum,
          "stu_address":req.body.stu_address,
          "stu_img":file,
          "teach_id":req.body.teach_id,
          "stu_time":(Date.parse(moment(req.body.stu_time))/1000)
      };
            db.table("student").where(`stu_id=${stu_id}`).update(data).then(function(affectRows){
               res.redirect('/teaStu/teaStu_list');
            }).catch(function(err){
                   
                if(err){

                  base.showMsg(res,"更新失败");
                  return false;
                }
            });           
        }
        });
    }
  });

};

module.exports.teaStuDelete=(req,res)=>{

 let stu_id=req.params.stu_id||0;

 let where=`stu_id=${stu_id}`;

 db.table('student').where(where).delete().then(
   
   (stuRows)=>{

         base.showMsg(res,'删除成功','/teaStu/teaStu_list');
         return false;

   }

  ).catch(
    
     (err)=>{

         if(err){
           base.showMsg(res,'删除失败','/teaStu/teaStu_list');
           return false;
         }

     }

  );







};





